package main.controller.admin;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import static com.mongodb.client.model.Filters.eq;

import com.mongodb.client.MongoCursor;
import main.GlobalConfig;
import main.RequestHelper;
import main.TimeHelper;
import main.database.AccountHelper;
import main.database.AudioHelper;
import main.database.DatabaseMan;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class AudioEditPageController {
    @RequestMapping(value="/audioedit")
    public String audioEditPage(HttpServletRequest request, ModelMap modelMap, @RequestParam(value="id") String id) {
        boolean isAdmin = false;

        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        isAdmin = AccountHelper.isAdminFromUUID(uuid);
        String account = AccountHelper.getAccountInfoFromUUID(uuid);

        String result;
        if (isAdmin) {
            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfArticle);
            FindIterable<Document> findIterable = collection.find(eq("_id", new ObjectId(id)));
            MongoCursor<Document> cursor = findIterable.iterator();

            String name = "";
            if (cursor.hasNext()) {
                name = cursor.next().get("title").toString();
            }

            List<String[]> audioList = AudioHelper.getAudioInfoFromArticleId(id);

            modelMap.put("audioList", audioList);
            modelMap.put("fictionId", id);
            modelMap.put("fictionName", name);
            modelMap.put("userName", account);
            modelMap.put("year2year", TimeHelper.getFormattedYear2Year());

            result = "/admin/audioEditPage";
        }
        else {
            result = "/admin";
        }
        return result;
    }
}
